package com.coai.twin.service

import org.influxdb.InfluxDB
import org.influxdb.InfluxDBFactory
import org.influxdb.dto.Point
import org.influxdb.dto.Query
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import javax.annotation.PostConstruct

@Service
class InfluxDBService {
    
    @Value("\${influxdb.url}")
    private lateinit var url: String
    
    @Value("\${influxdb.username}")
    private lateinit var username: String
    
    @Value("\${influxdb.password}")
    private lateinit var password: String
    
    @Value("\${influxdb.database}")
    private lateinit var database: String
    
    private lateinit var influxDB: InfluxDB
    
    @PostConstruct
    fun init() {
        influxDB = InfluxDBFactory.connect(url, username, password)
        influxDB.setDatabase(database)
        influxDB.enableBatch()
    }
    
    fun write(point: Point) {
        influxDB.write(point)
    }
    
    fun query(queryString: String): List<Map<String, Any>> {
        val result = influxDB.query(Query(queryString))
        
        // 简化的结果处理
        return result.results
            .flatMap { it.series ?: emptyList() }
            .flatMap { series ->
                series.values.map { values ->
                    series.columns.zip(values).toMap()
                }
            }
    }
}
